<template>
	<view class="content">
		<view class="margin-lr margin-top-lg">
			<view class="text-xl padding text-center margin-bottom">
				<!-- <image src="../../static/favicon.png" class="logo" /> -->
				<text class="text-xxl text-bold">{{ app.web.name }}</text>
			</view>
			<form class="radius">
				<view class="cu-form-group">
					<view class="title">账号</view>
					<input placeholder="请输入您的账号" name="userName" v-model="model.token" />
				</view>
				<view class="cu-form-group">
					<view class="title">密码</view>
					<input placeholder="请输入您的密码" name="password" password v-model="model.password" />
				</view>
				<view class="flex margin-tb">
					<a class="basis-lg cu-btn bg-blue lg radius" href="http://ids.xmu.edu.cn/authserver/login?service=http://cetpk.xmu.edu.cn/api/ecard">
						厦大统一认证登录
					</a>
					<button class="basis-sm margin-left cu-btn bg-green lg radius btn-login" @click="login">
						登录
					</button>
				</view>
				<view class="flex flex-direction margin-tb" v-if="canRegister" @click="register">
					<button class="cu-btn bg-white lg">
						其他人员（如派遣人员等）用户注册
					</button>
				</view>
			</form>
		</view>
	</view>
</template>

<script setup>
	import { reactive, ref, onMounted } from 'vue'
	import app from '@/app';
	import axios from "@/axios"
	import { isLogined, setCurrentUser, validateCurrentUser } from '@/configs/useCurrentUser'
	
	const loading = ref(false);
	const model = reactive({
	    token: "",
	    password: ""
	});
	const errors = ref("");
	
	const dashboard = "/pages/index/index";
	if (isLogined) {
	    app.redirectTo(dashboard);
	}
	
	function register () {
		uni.navigateTo({
			url: "/pages/login/register"
		})
	}
	
	async function login () {
	    loading.value = true;
	    let method = "POST";
	    let url = "/api/authorize/login";
	    let timestamp = (new Date()).valueOf();
	    let nounce = Math.random();
	    let token = model.token;
	    let pwd = app.sha1(model.password);
	    	
	    let signature = [method, url, timestamp, nounce, token, pwd].join('\n');
	    signature = app.sha256(signature);
	    	
	    let msg = await axios.post(url, {
	        token,
	        nounce,
	        timestamp,
	        signature
	    });
	    	
	    if (msg.success) {
	        await setCurrentUser(msg);
	        app.redirectTo(dashboard);
	    } else {
	        alert(msg.msg);
	    }
	    loading.value = false;
	}
	
	const canRegister = ref(false);
	const form = ref();
	async function readRegisterStatus () {
	    let msg = await axios.post("/api/applications/CanRegister");
	    canRegister.value = msg.success;
	}

	onMounted(async _ => {
		readRegisterStatus();
		await validateCurrentUser();
		if (isLogined) {
			uni.redirectTo({
				url: "/pages/index/index"
			})
		} 
	})
</script>

<style lang="less" scoped>
	.logo {
		width: 44rpx;
		height: 44rpx;
	}
</style>
